﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Framework;
using Web.Framework.Svc;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts;
using System.Web.UI;
using System.Configuration;
using System.Web.UI.HtmlControls;
using CrmContacto.Contracts.Contracts.Search;
using System.Web.UI.WebControls;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.Framework.Translate;
using CrmContacto.WebApp.Code.InnerClasses.FrontEnd;
using Web.Framework.Misc;
using CrmContacto.WebApp.Code;

namespace Web.CrmContacto.Code
{
    public abstract class BasePage : BaseWebPage
    {
        protected WebServiceHelper WebServiceHelper { get; set; }

        protected UIHelper UIHelper { get; set; }

        protected override void OnPreLoad(EventArgs e)
        {
            WebServiceHelper = new WebServiceHelper();
            WebServiceHelper.ServiceOptionsDefault = new ServiceOptions();
            WebServiceHelper.ServiceOptionsDefault.UserName = BaseWebPage.UserName;

            UIHelper = new UIHelper();
            UIHelper.companyId = BaseWebPage.CompanyId;
            UIHelper.WebServiceHelper = WebServiceHelper;

            LoadLocalization();

            base.LoadOperations(WebServiceHelper.GetOperationsForUser(BaseWebPage.ApplicationId, BaseWebPage.CompanyId, BaseWebPage.UserName));
            //masterPage.PreLoad(new List<string>());

            base.OnPreLoad(e);            
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if(this.Request[MiscClass.QueryShowDeleted] != null)
            {
                ExceptionManager.Instance.ShowMessage(LocalizationProvider.Instance["Bo.Message.RegistroEliminado"]);
            }

            if (this.Request[MiscClass.QueryShowSaveOk] != null)
            {
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            LinkButton lnkGuardar = FindControlRecursive(this, "lnkGuardar") as LinkButton;
            SetJavascriptForToAvoidConfirmLeave(lnkGuardar);
            lnkGuardar = FindControlRecursive(this, "BoCommandGuardar") as LinkButton;
            SetJavascriptForToAvoidConfirmLeave(lnkGuardar);
        }

        protected static void SetJavascriptForToAvoidConfirmLeave(LinkButton lnkGuardar)
        {
            if (lnkGuardar != null)
            {
                if (String.IsNullOrEmpty(lnkGuardar.OnClientClick))
                {
                    lnkGuardar.OnClientClick = "window.AppCommonObj.Guardando = true; return true;";
                }
                else
                {
                    if (lnkGuardar.OnClientClick.Contains("return"))
                    {
                        lnkGuardar.OnClientClick = "  var fun = function(){" + lnkGuardar.OnClientClick + "}; if( fun() ) {window.AppCommonObj.Guardando = true; return true;} else {return false;}";
                    }
                    else
                    {
                        lnkGuardar.OnClientClick = " if( " + lnkGuardar.OnClientClick + " ) {window.AppCommonObj.Guardando = true; return true;} else {return false;}";
                    }
                }
            }
        }

        public static List<ReportingConfiguration> GetReportingConfiguration(HttpApplicationState application)
        {
            List<ReportingConfiguration> reportingConfigurationList;
            if (application[MiscClass.ReportingConfigurationKey] == null)
            {
                WebServiceHelper wsHelper = new WebServiceHelper();
                reportingConfigurationList = wsHelper.GetReportingConfiguration(string.Empty, BasePage.CompanyId);

                application[MiscClass.ReportingConfigurationKey] = reportingConfigurationList;
            }
            else
            {
                reportingConfigurationList = (List<ReportingConfiguration>)application[MiscClass.ReportingConfigurationKey];
            }

            return reportingConfigurationList;
        }

        public void LoadContextActions(List<LinkButton> linkButtons)
        {
            SiteMaster siteMaster = (SiteMaster)this.Master;
            siteMaster.LoadContextActions(linkButtons);
        }

        protected void funcionalidadNoImplementadaButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlFuncionalidadNoImplementada, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected NavigationContext NavigationContext
        {
            get
            {
                NavigationContext nav = StoreHelper.GetObject(MiscClass.NavigationContextKey) as NavigationContext;
                if (nav == null)
                {
                    nav = new NavigationContext();
                    NavigationContext = nav;
                }

                return nav;
            }
            set
            {
                StoreHelper.StoreObject(MiscClass.NavigationContextKey, value);
            }
        }       
        
        protected void SetJavascriptForClientClickDirtyChech(LinkButton lnkBtn)
        {
           // lnkBtn.OnClientClick = "if(document.DirtyCheck.areControlsDirty()) {return confirm('" + LocalizationProvider.Instance["Bo.Messages.DirtyMessageConfirmContinue"] + "'); } else {return true;}";
        }

        protected void SetJavascriptForDeleteRecord(LinkButton lnkBtn, string registro)
        {            
            lnkBtn.OnClientClick = "if(confirm('" + string.Format(LocalizationProvider.Instance["Bo.Messages.ConfirmarEliminarRegistro"], registro) + "')){ window.AppCommonObj.Guardando = true; return true;} else {return false;} ";
        }

        protected void SetJavascriptForDeleteRecord(ImageButton lnkBtn, string registro)
        {
            lnkBtn.OnClientClick = "if(confirm('" + string.Format(LocalizationProvider.Instance["Bo.Messages.ConfirmarEliminarRegistro"], registro) + "')){ window.AppCommonObj.Guardando = true; return true;} else {return false;} ";
        }

        protected void SetJavascriptForClientClickDirtyChech(ImageButton lnkBtn)
        {
            //lnkBtn.OnClientClick = "if(document.DirtyCheck.areControlsDirty()) {return confirm('" + LocalizationProvider.Instance["Bo.Messages.DirtyMessageConfirmContinue"] + "'); } else {return true;}";
        }

        private void LoadLocalization()
        {
            string lenguajePorDefecto = ConfigurationManager.AppSettings["LenguajePorDefecto"];
            if (String.IsNullOrEmpty(lenguajePorDefecto))
            {
                throw new Exception("Debe configurar el lenguaje por defecto");
            }

            HtmlGenericControl js = new HtmlGenericControl("script");
            js.Attributes.Add("type", "text/javascript");
            js.Attributes.Add("src", string.Format("/Scripts/Localization/Localization.{0}.js", lenguajePorDefecto));
            this.Page.Header.Controls.Add(js);
        }

        public static void ClearPaises(HttpContext context)
        {
            context.Cache.Remove("paises");
            LocalizationHelper.ReInitialize();
        }

        public static List<Pais> GetPaises(HttpContext context)
        {
            List<Pais> paisesList = context.Cache["paises"] as List<Pais>;
            if (paisesList == null)
            {
                paisesList = WebServiceHelper.GetPaises();
                context.Cache["paises"] = paisesList;
            }

            return paisesList;
        }

        public List<Pais> GetPaises()
        {
            return BasePage.GetPaises(this.Context);
        }

        public static void ClearProvincias(HttpContext context)
        {
            var enumerator = context.Cache.GetEnumerator();
            while(enumerator.MoveNext())
            {
                if(enumerator.Key.ToString().Contains("provincias"))
                {
                    context.Cache.Remove(enumerator.Key.ToString());
                }
            }
            
            LocalizationHelper.ReInitialize();
        }

        public static List<MaestroBase> GetProvincias(HttpContext context, int paisId)
        {
            List<MaestroBase> provinciasList = context.Cache["provincias" + paisId.ToString()] as List<MaestroBase>;
            if (provinciasList == null)
            {
                provinciasList = WebServiceHelper.GetProvincias(paisId);
                context.Cache["provincias" + paisId.ToString()] = provinciasList;
            }

            return provinciasList;
        }

        public List<MaestroBase> GetProvincias(int paisId)
        {
            return GetProvincias(this.Context, paisId);
        }

        public static void ClearTipoDocumento(HttpContext context)
        {
            var enumerator = context.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Key.ToString().Contains("tipoDocumento"))
                {
                    context.Cache.Remove(enumerator.Key.ToString());
                }
            }           
        }

        public static List<MaestroBase> GetTipoDocumento(HttpContext context, int paisId)
        {
            List<MaestroBase> tipoDocumentoList = context.Cache["tipoDocumento" + paisId.ToString()] as List<MaestroBase>;
            if (tipoDocumentoList == null)
            {
                tipoDocumentoList = WebServiceHelper.GetTipoDocumento(paisId);
                context.Cache["tipoDocumento" + paisId.ToString()] = tipoDocumentoList;
            }

            return tipoDocumentoList;
        }

        public List<MaestroBase> GetTipoDocumento(int paisId)
        {
            return GetTipoDocumento(this.Context, paisId);
        }

        public static void ClearCategorias(HttpContext context)
        {
            var enumerator = context.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Key.ToString().Contains("GetCategorias"))
                {
                    context.Cache.Remove(enumerator.Key.ToString());
                }
            }
        }

        public static List<MaestroBase> GetCategorias(HttpContext context, int empresaId)
        {
            List<MaestroBase> categoriasList = context.Cache["GetCategorias" + empresaId.ToString()] as List<MaestroBase>;
            if (categoriasList == null)
            {
                categoriasList = WebServiceHelper.GetCategoriasDeContacto(new MaestroBaseSearch() { EmpresaId = empresaId });
                context.Cache["GetCategorias" + empresaId.ToString()] = categoriasList;
            }

            return categoriasList;
        }

        public List<MaestroBase> GetCategorias(int empresaId)
        {
            return GetCategorias(this.Context, empresaId);
        }

        public static void ClearPuntosDeVenta(HttpContext context)
        {
            context.Cache.Remove("GetPuntosDeVenta" + BasePage.CompanyId.ToString());
        }
         
        public static List<PuntoDeVenta> GetPuntosDeVenta(HttpContext context, int companyId)
        {
            List<PuntoDeVenta> puntosDeVentaList = context.Cache["GetPuntosDeVenta" + companyId.ToString()] as List<PuntoDeVenta>;
            if (puntosDeVentaList == null)
            {
                PuntoDeVentaSearch search = new PuntoDeVentaSearch();
                search.EmpresaId = companyId;
                search.Activo = true;
                puntosDeVentaList = WebServiceHelper.GetPuntoDeVentaDto(search);
                context.Cache["GetPuntosDeVenta" + companyId.ToString()] = puntosDeVentaList;
            }

            return puntosDeVentaList;
        }

        public List<PuntoDeVenta> GetPuntosDeVenta(int companyId)
        {
            return GetPuntosDeVenta(this.Context, companyId);
        }

        public static void ClearConfigurationCache(Page page)
        {
            page.Cache.Remove("companyConfigurationList");
            page.Cache.Remove("companyConfigurationListKeyValue");
            companyConfigurationList = null;
            companyConfigurationListKeyValue = null;
        }

        private static List<CompanyConfiguration> companyConfigurationList;
        public static List<CompanyConfiguration> GetCompanyConfigurationList(Page page)
        {
            if (companyConfigurationList == null)
            {
                if (page.Cache["companyConfigurationList"] == null)
                {
                    companyConfigurationList = WebServiceHelper.GetCompanyConfigurations();
                    page.Cache["companyConfigurationList"] = companyConfigurationList;
                }
                else
                {
                    companyConfigurationList = (List<CompanyConfiguration>)page.Cache["companyConfigurationList"];
                }
            }

            return companyConfigurationList;
        }

        private static List<CompanyConfigurationKeyValue> companyConfigurationListKeyValue;
        public static List<CompanyConfigurationKeyValue> GetCompanyConfigurationKeyValue(Page page, int companyId)
        {
            if (companyConfigurationListKeyValue == null)
            {
                if (page.Cache["companyConfigurationListKeyValue"] == null)
                {
                    companyConfigurationListKeyValue = new List<CompanyConfigurationKeyValue>();
                    foreach (var d in WebServiceHelper.GetCompanyConfigurationKeyValues(companyId))
                    {
                        CompanyConfigurationKeyValue c = new CompanyConfigurationKeyValue();
                        c.CompanyId = companyId;
                        c.Key = d.Key;
                        c.Value = d.Value;
                        companyConfigurationListKeyValue.Add(c);
                    }

                    page.Cache["companyConfigurationListKeyValue"] = companyConfigurationListKeyValue;
                }
                else
                {
                    companyConfigurationListKeyValue = (List<CompanyConfigurationKeyValue>)page.Cache["companyConfigurationListKeyValue"];
                }
            }

            return companyConfigurationListKeyValue;
        }
    }
}